package article10.equals;

/**
 * Class with a typical equals method
 *
 * @Author: cctv
 * @Date: 2019/4/3 14:16
 */
public class PhoneNumber {

    private final short areaCode, prefix, lineNum;

    public PhoneNumber(int areaCode, int prefix, int lineNum) {
        this.areaCode = rangeCheck(areaCode, 999, "area code");
        this.prefix = rangeCheck(prefix, 999, "prefix");
        this.lineNum = rangeCheck(lineNum, 999, "lin num");
    }

    private static short rangeCheck(int val, int max, String arg) {
        if (val < 0 || val > max) {
            throw new IllegalArgumentException(arg + ":" + val);
        }
        return (short) val;
    }

    @Override
    public boolean equals(Object o) {
        //使用==操作符检查“参数是否为这个对象的引用”
        if (o == this) {
            return true;
        }
        //使用instanceof操作符检查“参数是否为正确的类型”
        if (!(o instanceof PhoneNumber)) {
            return false;
        }
        //把参数转换成正确的类型
        PhoneNumber pn = (PhoneNumber) o;
        //对于该类中的每一个“关键”域，检查参数中的域是否与该对象中对应的域相匹配
        return pn.lineNum == lineNum && pn.prefix == prefix && pn.areaCode == areaCode;
    }



}
